package br.com.mayco.persistence;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 * @author Mayco Lucian
 * @since 25/02/2013
 * version 1.0.0
 */

public class Database {

    private static Database db;

    public static Database getDb() {
        if (db == null) {
            db = new Database();
        }
        return db;
    }

    private EntityManagerFactory emfactory;
    private String persistenceUnit = DatabaseConfig.PERSISTENCE;

    public EntityManagerFactory getEmfactory() {
        if (emfactory == null) {
            emfactory = Persistence.createEntityManagerFactory(persistenceUnit);
        }
        return emfactory;
    }

    public void setPersistenceUnit(String persistenceUnit) {
        this.persistenceUnit = persistenceUnit;
    }

    public String getPersistenceUnit() {
        return persistenceUnit;
    }

    public boolean isOpen() {
        return getEmfactory().isOpen();
    }

    public EntityManager createEntityManager() {
        return getEmfactory().createEntityManager();
    }

    public void close() {
        getEmfactory().close();
    }

}